{% extends 'base.html' %}
{% load i18n %}
{% load static %} {# Ensure static is loaded #}

{% block title %}{% trans "我的田块" %} - {{ block.super }}{% endblock %}

{% block extra_head %} {# Add Leaflet CSS in the head #}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<style>
    #fieldMap {
        height: 400px; /* Define map container height */
        width: 100%;
        margin-bottom: 1.5rem; /* Space below map */
        border-radius: 0.375rem;
        border: 1px solid var(--app-border-color);
        box-shadow: var(--app-card-shadow);
    }
</style>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-map me-2"></i> {% trans "我的田块" %}</h1>
    <a href="{% url 'field_management:field_add' %}" class="btn btn-success"><i class="bi bi-plus-lg"></i> {% trans "添加新田块" %}</a>
</div>

{# Map Container #}
<div id="fieldMap"></div>

{# Existing Field List #}
<h2 class="h4 mt-4 mb-3">{% trans "田块列表" %}</h2>
{% if fields %}
    <div class="list-group shadow-sm">
        {% for field in fields %}
        <a href="{{ field.get_absolute_url }}" class="list-group-item list-group-item-action field-card">
            {# ... existing list item content ... #}
             <div class="d-flex w-100 justify-content-between">
                <h5 class="mb-1 text-success">{{ field.name }} {% if not field.latitude or not field.longitude %}<small class="text-warning fw-normal">({% trans "无坐标" %})</small>{% endif %}</h5>
                <small class="text-muted">{{ field.area }} {% trans "亩" %}</small>
            </div>
            <p class="mb-1">
                <i class="bi bi-geo-alt-fill text-secondary me-1"></i> {{ field.location|default:_("未提供位置") }} <br>
                <small class="text-muted">
                    <i class="bi bi-bricks text-secondary me-1"></i> {% trans "土壤" %}: {{ field.soil_type|default:_("未知") }},
                    <i class="bi bi-water text-secondary ms-2 me-1"></i> {% trans "灌溉" %}: {{ field.irrigation_source|default:_("未知") }}
                </small>
            </p>
            <small class="text-muted">{% trans "最后更新" %}: {{ field.updated_at|date:"Y-m-d H:i" }}</small>
        </a>
        {% endfor %}
    </div>
    {% include 'partials/_pagination.html' %}
{% else %}
    <div class="alert alert-info text-center" role="alert">
       <i class="bi bi-info-circle me-2"></i> {% trans "您还没有添加任何田块信息。" %}
       <a href="{% url 'field_management:field_add' %}" class="alert-link ms-2">{% trans "立即添加" %}</a>
    </div>
{% endif %}
{% endblock %}

{% block extra_js %} {# Add Leaflet JS and map initialization script #}
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 1. Initialize Map
        // Try to center on the first field with coordinates, otherwise default view
        let initialCenter = [31.2304, 121.4737]; // Default center (e.g., Shanghai)
        let initialZoom = 10; // Default zoom level

        // Map initialization (set default view first)
        const map = L.map('fieldMap').setView(initialCenter, initialZoom);

        // 2. Add Tile Layer (Map background) - OpenStreetMap is free
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // 3. Fetch Field Data and Add Markers
        const locationsUrl = "{% url 'field_management:field_locations_json' %}";
        const markers = []; // To hold marker objects

        fetch(locationsUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(fields => {
                if (fields && fields.length > 0) {
                    fields.forEach((field, index) => {
                        if (field.latitude && field.longitude) {
                            const lat = field.latitude;
                            const lon = field.longitude;
                            const marker = L.marker([lat, lon]);

                            // Create popup content
                            const popupContent = `
                                <strong>${field.name}</strong><br>
                                面积: <span class="math-inline">\{field\.area\} 亩<br\>
<a href="{field.detail_url}">查看详情</a> `; marker.bindPopup(popupContent); markers.push(marker); // 将 marker 添加到数组

                            // If it's the first field, set map center
                            if (index === 0) {
                                 initialCenter = [lat, lon];
                                 initialZoom = 13; // Zoom closer for the first field
                                 map.setView(initialCenter, initialZoom);
                            }
                        }
                    });

                    // Add all markers to the map in a FeatureGroup
                    if (markers.length > 0) {
                        const markerGroup = L.featureGroup(markers).addTo(map);
                        // Optional: Fit map bounds to show all markers
                        // Be careful, if markers are very far apart, zoom might be too far out
                        if (markers.length > 1) { // Only fit bounds if more than one marker
                             map.fitBounds(markerGroup.getBounds().pad(0.3)); // Add padding
                        }
                    } else {
                         console.warn("No fields with coordinates found to display markers.");
                    }

                } else {
                     console.log("No field data received or fields array is empty.");
                }
            })
            .catch(error => {
                console.error('Error fetching field locations:', error);
                // Optionally display a user-friendly message on the page
                const mapDiv = document.getElementById('fieldMap');
                mapDiv.innerHTML = '<div class="alert alert-warning">无法加载地图标记数据。</div>';
                mapDiv.style.height = 'auto'; // Adjust height if map fails
            });

        // Add scale control
        L.control.scale({ imperial: false }).addTo(map);

    });
</script>
{% endblock %}